<template>
  <div id="lottery" class="show" :style="{backgroundImage:'url('+bgUrl+')'}">
    <div @click="goBack" class="go-back">春招活动</div>
    <div class="lottery-num">
      <p>恭喜你！</p>
      <p>还有{{numberSum}}次抽奖机会</p>
    </div>
    <div class='yq-lotteryBox'>
        <div class="lottery">
            <div class="turnplate"  >
                <canvas class="item" id="wheelCanvas" :width="canvasWidth" :height="canvasWidth"></canvas>
                <img  class="pointer" :src="pointImg"/>
            </div>
        </div>
    </div>
    <div class="start-btn"  @click="start">
      <div class="start-font">开始抽奖</div>
    </div>
    <div class="record-btn" @click="showWinData">
      <div class="record-font">抽奖记录</div>
    </div>
    <div class="rule-btn" @click="showRule=true">
      <div class="rule-font">抽奖规则</div>
    </div>
    <div >
      <!-- v-if="luckdrawSubject.cj_winners_show" <div class="reward-title"> 中奖列表</div> -->
      <div class="reward-list">
        <rewardList ></rewardList >
      </div>
    </div>

    <!-- 规则 -->
    <van-overlay class="change-bg" :show="showRule" @click="showRule = false">
      <div class="wrapper-rule" >
       
      <p>抽奖规则：</p> 
      <p>1.登录后完善简历至80%可获得一次抽奖机会</p>
      <p>2.简历完善度如何到80%：填写基本信息、教育经历、工作经历和项目经历即可到80%。若无工作经历，可以填写为无。</p>
      <p>3.返回春招节页面分享春招节链接至朋友圈，可获得额外2次抽奖机会。</p>
      
      </div>
    </van-overlay>

    <!-- 简历完善弹窗 -->
    <van-overlay :show="overlayShow" @click="overlayShow = false">
      <div class="wrapper" @click.stop>
        <img class="wrapper-confirm" src="../../../assets/confirm.png" alt="">
        <img @click="closeOverLay" class="wraper-close" src="../../../assets/close.png" alt="">
        <div class="resume-block" >
          简历完善率到80%，即可进行抽奖哦。
          <p>学姐提示：填写基本信息、教育经历、工作经历即可到达80%哦</p>
          
        </div>
        <div class="resume-btn" @click="goComplete">前去完善简历 ({{countTimer+'s'}})</div>
      </div>
    </van-overlay>

    <!-- 获奖弹窗 -->
      <van-overlay :show="overlayShow1" @click="overlayShow1 = false">
      <div class="wrapper1" :style="{backgroundImage:'url('+bgUrl1+')'}" @click.stop>
        <img class="win-icon" src="../../../assets/win-icon.gif" alt="">
        <img @click="winClose" class="win-close" src="../../../assets/win-close.png" alt="">
        <div class="win-block">
          <div class="win-title">{{WinInfo.it_title}}</div>
          <div class="win-code">兑奖码: {{WinInfo.cj_code}}</div>
          <div class="win-tips">
            <div>
              下载/登录一览APP，在【消息】/【我】模块找到一览小助手，将领奖凭证发给一览小助手即可领取奖品
            </div>
          </div>
          
        </div>
          <div class="win-save" @click="saveWinData">截图领奖凭证</div>
          <div class="win-down" @click="download">下载一览APP</div>
      </div>
    </van-overlay>

    <!-- 分享弹窗 -->
    <van-overlay :show="overlayShow2" >
      <div class="wrapper" @click.stop>
        <img class="share-close" @click="closeOverlayShow2"  src="../../../assets/win-close.png" alt="">
        <img class="share-confirm tip-title" src="../../../assets/tip-title.png" alt="">
        <img class="share-confirm tip-eye" src="../../../assets/tip-eye.png" alt="">
        <div class="share-tip">
          <p>1.【求职小贴士】选择正规求职网站,避免上当受骗。</p>
          <p>2.【面试小贴士】提前准备好面试文稿，同时备好纸笔，方便随时记录相关内容。</p>
          <p>3.【面试小贴士】面试时仪容整齐干净是基本礼貌喔，谈话时面带微笑，神经专注也有助於给他人好的第一印象。</p>
          <p>4.【面试小贴士】勇于提问：在充分了解公司及岗位的情况下，可以多多提问一些有针对性及有建设性的问题。</p>
          <p>5.【面试小贴士】谈吐得体，口齿清晰。注意把握好语速语调，确保对方能够听得清楚准确。</p>
          
        </div>

        

        <!-- <img class="share-confirm" src="../../../assets/confirm2.png" alt=""> -->
        <!-- <img  @click="shareAddNum"  class="share-point" src="../../../assets/confirm-point.png" alt=""> -->
        <div class="share-msg">{{shareMsg}}</div> 
        <div v-if="!isWin">
          <img  class="share-confirm tip-btn" src="../../../assets/tip-btn.png" alt="">
        <div class="share-font">
          <p>将春招链接分享到朋友圈。</p> 
          <p>分享过后回到该页面可再次获得<span style="font-size: 11px;font-weight: bold;color: #ed3a71;">2次</span>抽奖机会哦</p>
        </div>
        </div>
        
        <div v-else class="share-font share-again" @click="startAgain">
          再次抽奖
        </div>
        <div  class="share-font back-spring" @click="goBack2">
          返回春招活动
        </div>

        <van-overlay :show="overlayShow3" >
          <div class="wrapper" >
            <img class="share-leave-confirm" src="../../../assets/leave-confirm.png" alt="">
            <div class="leave-content">
              <p>离开后将错过更多抽奖机会哦，</p> 
              <p>是否狠心离开？</p>
            </div>
            <div class="leave-tip" @click="shareData">
              继续分享
            </div>
            <div class="leave-font" @click="shareLeave">
              狠心离开
            </div>
            
          </div>
        </van-overlay>

      </div>
    </van-overlay>

    <!-- <van-button type="danger"  @click="saveImg">截图</van-button>
    <van-button type="danger"  @click="showOverlay">弹窗</van-button> -->

  </div>
</template>

<script>
import wx from "weixin-js-sdk";
import wxShareMixin from "./wxShareMixin";
import handle from "@/utils/handle.js";
import '@/utils/awardRotate.js'
import html2canvas from 'html2canvas'
import { Dialog } from 'vant';

import rewardList from './components/rewardList.vue'

export default {//TIP: 整个账号体系的账号绑定只是引导,非强制(可能存在手机未绑定的情况)
  mixins: [wxShareMixin],
  components: {
    rewardList,
  },
  data() {
    return {
      imageUrl:process.env.NODE_ENV === 'production' ?'http://img106.job1001.com/':'http://192.168.60.200/job1001images/',//bg图片路径
      springUrl:'https://m5.yl1001.com/marketing/spring-recruit/index.html#/',//春招url
      resumeUrl:'',
      bgUrl:require('@/assets/lotteryBg.gif'),
      bgUrl1:require('@/assets/winBg.png'),
      bgUrl2:require('@/assets/turnplate-bg1.png'),
      pointImg:require('@/assets/turnplate-pointer1.png'),
      canvasWidth:422,
      turnplate:{
        outsideRadius:200,			//大转盘外圆的半径
        textRadius:100,				//大转盘奖品位置距离圆心的距离
        insideRadius:40,			//大转盘内圆的半径
        startAngle:0,				//开始角度
        bRotate:false				//false:停止;ture:旋转
      },
      winnerList:[//超过一百,后台的几率直接为0
          
      ],  //奖品列表
      luckdrawSubject:{},
      iscomplete:true,//简历是否完善

      numberSum:0,//抽奖次数
      isWin: false, //中奖状态
      WinInfo:{},

      cj_uid:'',  //抽奖用户id
      isBindMobile:false,  //抽奖用户是否绑定手机号
      isShare:false,  //是否分享

      showRule:false,
      overlayShow:false,  //简历完善弹窗值
      overlayShow1:false, //获奖弹窗值
      overlayShow2:false, //分享弹窗值
      overlayShow3:false, //离开弹窗值
      countTimer:5,
      shareMsg:'谢谢惠顾',

      setIntervalTimer:null,
    };
  },

  beforeRouteEnter (to, from, next) {
    next(vm=>{
      // if(vm.showType=='architecture')return; //需要考虑建筑学会的状态
      // if(vm.$store.state.countNum==1){//第一次进来才跳转,后面就不跳转了
      //   vm.checkBindMobile().then(res=>{//4001 未来登录 3010 未绑定(拿到openid的情况下)
      //     let code=res.data.code
      //     console.log('--------------路由index--------',res);
      //     if(code==3010){
      //       vm.$router.replace({
      //         name: 'bindPhone',
      //         query: {
      //           live_id: vm.liveId,
      //         }
      //       })
      //     }else if(code==4001){//这里未登录还是放到下面去判断

      //     }
      //   }).catch(err=>{

      //   })
      // }
    })
  },
 
  computed: {
    cj_id(){//抽奖
      return this.$route.query["cj_id"];
    },
    liveId() {
      return this.$route.query["live_id"];
    },
    person_id() {
      return (
        this.$route.query["person_id"] || localStorage.getItem("person_id")
      );
    },
    openid() {
      let openid =
        this.$route.query["openid"] || localStorage.getItem("openid");
      return openid
        ? openid.indexOf(",") >= 0
          ? openid.split(",")[1]
          : openid
        : "";
      // return this.GetQueryString("openid");
    },
    userinfo() {
      return this.$route.query.userinfo || localStorage.getItem("userinfo");
    },
  },

  async created () {
    
  },
  async mounted() {
    this.checkLoginStatus()
    this.getLuckdrawSubject()
    await this.getLuckdrawPrizeList()
    await this.joinLuckdrawSubject()
    await this.checkUserPrizeNum()
    await this.checkCjUserIsTrue()
    this.drawRouletteWheel()
    this.$store.commit('addCountNum')
    // 账号登录逻辑换到login页面去操作
    
    return;

    //登录抽离后这里用不到了(电脑调试可以使用这一段代码)
    if (!this.openid) {
      var jump = encodeURIComponent(window.location.href);
      window.location.href = //http://www.yl1001.com/personServe/oauth_connect/login.php?connect_source=wechat&act=forward&http_referer=
        "http://www.job1001.com/personServe/oauth_connect/login.php?connect_source=wechat&act=forward&fromtype=external&http_referer=" +
        // 'http://www.yl1001.com/personServe/oauth_connect/login.php?connect_source=wechat&act=forward&http_referer='+
        jump;
      return;
    }
    if (this.openid && !this.userinfo) {
      console.log("this.openid", this.openid);

    }
    // 鉴定权限 end
    if (this.userinfo) {
      localStorage.setItem("userinfo", this.userinfo);
      console.log(this.userId);
      // window.location.href = `${window.location.origin}/show?liveId=${this.liveId}&article_id=${this.article_id}&openid=${this.openid}`
      // debugger
      this.$router.replace({
        name: "show",
        query: {
          cj_id: this.cj_id,
          person_id: this.person_id,
          openid: this.openid,
          userId: this.userId || localStorage.getItem("userId"),
        },
      });
    }
  },
  methods: {
    goBack(){
      location.href=this.springUrl
    },
    goBack2(){
      if(!this.isShare){
        this.overlayShow2=false
        this.addUserPrizeNumDeal()
      }
      setTimeout(()=>{
        location.href=this.springUrl
      },1000)
      
    },
    checkLoginStatus(){//检查登录状态
      this.$http({
        url: this.$http.adornUrl(`index/login/checkLoginStatus`, "proxyPhp"),
      }).then((res) => {
        console.log("登录信息", res);
        const isYlDebug =
          navigator.userAgent.toLowerCase().indexOf("yl_debug") > 0;
          if (isYlDebug) { // 如果是yldebug本地调试不检测登录结果
            return
          }
        if (res.data.code == 200) {
          //统一使用person_id;来评论
          localStorage.setItem("cks_sy", res.data.data.cks_sy);
          localStorage.setItem("person_id", res.data.data.person_id);

          var ua = navigator.userAgent.toLowerCase();
          let isWeixin = ua.indexOf("micromessenger") != -1;
          return;
        } else {
          //做一次登出操作,把存储信息删除
          window.localStorage.removeItem("openid");
          window.localStorage.removeItem("unionid");
          window.localStorage.removeItem("person_id");
          window.localStorage.removeItem("cks_sy");
          this.$nextTick(() => {
            if (this.showType == 'architecture') {
              this.goarchitectureInfo()
              return
            }
            this.$router.push({
              name: "login",
              query: {
                cj_id: this.cj_id,
              },
            });
          });
        }
      });
      this.$nextTick(() => {
        this.init();   
      });
    },
    checkBindMobile(){//检测用户是否绑定过手机号(这个放在直播页面进行判断跳转,是否可以根据路由守卫来直接判断)
      console.log('计数',this.$store.state.countNum); 
      if(this.showType=='architecture')return;
      if(this.$store.state.countNum==1){
        this.$http({
          url: this.$http.adornUrl('index/user/checkBindMobile','proxyPhp'),
          method: "post",
        }).then(res=>{//4001 未来登录 3010 未绑定(拿到openid的情况下)
            let code=res.data.code
            console.log('--------------路由index--------',res);
            if(code==3010){
              this.$router.replace({
                name: 'bindPhone',
                query: {
                  cj_id: this.cj_id,
                }
              })
            }else if(code==4001){//这里未登录还是放到下面去判断
  
            }
          }).catch(err=>{
  
          })
      }
    },

    //是否完善
    async checkResumeComplete(){
      await this.$http({
        url: this.$http.adornUrl(`luckdraw/index/checkResumeComplete`,'proxyXlh'),
        method: "post",
        data: {
          // person_id:this.person_id,
          cj_id:this.cj_id
        }
      }).then((res) => {
        console.log(res);
        if(res.data.status=='FAIL'){//完善简历
          if(res.data.code==4001){
            return
          }
          this.showOverlay() //出现弹窗

          this.iscomplete=false//出现完善简历弹窗,5s倒计时
          // Dialog.confirm({
          //   title: '完善简历',
          //   message: '简历完善率到80%，即可进行抽奖哦。学姐提示：填写基本信息、教育经历、工作经历即可到达80%哦',
          //   className:'vant-dialog'
          // })
          // .then(() => {
            //可以直接使用正则拼接
            console.log(111,res.data.data.my_center_url);//'http://1001.yl1001.com/myNew/m_3g.php?mode=resume&doaction=ResumeUpdate&detail=index&live_id=&fromtype=url_token&token=CS7aw18DlD31VyNMX1eeCm13bu1W7nT'.split('&')
            let url=res.data.data.my_center_url
            this.resumeUrl=url
            // let urlArr=url.split('&')
            // console.log(urlArr);
            // for(let i=0;i<urlArr.length;i++){
            //   if(urlArr[i]=="live_id="){
            //     urlArr[i]="live_id="+this.liveId
            //   }
            // }
            // let newUrl=urlArr.join('&')
            // console.log('加上id的url',newUrl);
            
            // window.location.href=url//'http://'+ 有的没有
          // })
         
        }else{//投递
          this.iscomplete=true
        }
        console.log("是否完善", res);
      });
    },

    async joinLuckdrawSubject(){//无绑定手机号码，会被打回
      await this.$http({
        method: "get",
        url: this.$http.adornUrl(`luckdraw/index/joinLuckdrawSubject`, "proxyXlh"),
        params:{
          cj_id:this.cj_id,
        }
      }).then(res=>{
        this.cj_uid=res.data.info.cj_uid
        this.isBindMobile=true
        // console.log(res.data,2222222);
        // if(res.data.status=='FAIL'){//此时已经添加了手机
        //   this.isBindMobile=true
        // }else{
        //   this.isBindMobile=false
        // }
      })
    },
    async checkUserPrizeNum(){//判断抽奖次数(抽奖次数+额外抽奖次数)
      await this.$http({
        method: "get",
        url: this.$http.adornUrl(`luckdraw/index/checkUserPrizeNum`, "proxyXlh"),
        params:{
          cj_id:this.cj_id,
          cj_uid:this.cj_uid,
        }
      }).then(res=>{
        if(res.data.code==200){
          this.numberSum=res.data.data.sums  //res.data.data.sums
          console.log(111,res.data.data.cj_user_is_share);
          this.isShare=res.data.data.cj_user_is_share=='1'?true:false
        }
        console.log(res.data,3333);
      })
    },
    async checkCjUserIsTrue(){//判断是否中奖 TODO,中奖的状态值还是有些不清晰
      await this.$http({
        method: "get",
        url: this.$http.adornUrl(`luckdraw/index/checkCjUserIsTrue`, "proxyXlh"),
        params:{
          cj_id:this.cj_id,
        }
      }).then(res=>{
        if(res.data.code==200){//没有中奖
          this.isWin=false
        }else{//拿到中奖信息
          this.isWin=true
          this.WinInfo=res.data.data||{}
        }
      })
    },
    async addUserTrueDeal(cj_item_id){//判断中奖人
      await this.$http({
        method: "get",
        url: this.$http.adornUrl(`luckdraw/index/addUserTrueDeal`, "proxyXlh"),
        params:{
          cj_id:this.cj_id,
          cj_item_id,
        }
      }).then(res=>{
      })
    },
    async deductUserPrizeNumDeal(){//减除抽奖数,拿到抽奖值
      await this.$http({
        method: "get",
        url: this.$http.adornUrl(`luckdraw/index/deductUserPrizeNumDeal`, "proxyXlh"),
        params:{
          cj_id:this.cj_id,
        }
      }).then(res=>{
        //TODO 拿到抽奖数
        if(res.data.code==200){
          let data=res.data.info
          this.numberSum=Number(data.cj_prize_num)+Number(data.cj_extra_prize_num)
        }else{
          this.numberSum=0
        }
        this.checkUserPrizeNum()
        
      })
    },
    async addUserPrizeNumDeal(){//添加抽奖次数(用于分享)
      await this.$http({
        method: "get",
        url: this.$http.adornUrl(`luckdraw/index/addUserPrizeNumDeal`, "proxyXlh"),
        params:{
          cj_id:this.cj_id,
        }
      }).then(res=>{
        //TODO 拿到抽奖数
        if(res.data.code==200){
          let data=res.data.info
          this.numberSum=Number(data.cj_prize_num)+Number(data.cj_extra_prize_num)
        }
      })
    },

    async getLuckdrawSubject(){//抽奖基本信息
      await this.$http({
        method: "get",
        url: this.$http.adornUrl(`luckdraw/index/getLuckdrawSubject`, "proxyXlh"),
        params:{
          cj_id:this.cj_id
        }
      }).then(res=>{
        if(res.data.code==200){
          this.luckdrawSubject=res.data.data
          document.title=this.luckdrawSubject.cj_title
        }
      })
    },
    async getLuckdrawPrizeList(){//抽奖奖品列表
      await this.$http({
        method: "get",
        url: this.$http.adornUrl(`luckdraw/index/getLuckdrawPrizeList`, "proxyXlh"),
        params:{
          cj_id:this.cj_id,
          page:0,
          page_size:10
        }
      }).then(res=>{
        if(res.data.code==200){
          let list=res.data.data
          this.winnerList=handle.bubble(list)
          this.$forceUpdate()
          // this.winnerList=list.sort((num1, num2) => {//让最大的(未中奖)排在最前面(rate必须为数字)
          //   return (Number(num1.rate) - Number(num2.rate)) < 0
          // })
          let a=handle.bubble(list) //不生效
          console.log('列表1',this.winnerList,list[0],a[0]);
          // this.winnerList=res.data.data
          
          // this.winnerList.map(item=>{
          //   item.it_pic=this.imageUrl+item.it_pic //也可以在绘制时加上
          // })
        }
      })
    },
    drawRouletteWheel() {  //渲染canvas
      var canvas = document.getElementById("wheelCanvas");
      let num = this.winnerList.length;
      var width = this.canvasWidth/2
      // let arc = Math.PI / (num / 2);
      let randomCol=['#064cc1','#ffe611','#f33072','#ffffff','#ed3a71','#0fc0ce']
      if (canvas.getContext) {
        var arc = Math.PI / (num/2);
        var ctx = canvas.getContext("2d");
        //在给定矩形内清空一个矩形
        ctx.clearRect(0,0,width * 2,width * 2);
        //strokeStyle 属性设置或返回用于笔触的颜色、渐变或模式  
        ctx.strokeStyle = "#fff";

        for (let i = 0; i < num; i++) {
          let angle = 0 + i * arc;
          ctx.save();

          // ctx.fillStyle=randomCol[i];
          if ((i + 1) % 2 == 0) {
            ctx.fillStyle = "#ffe611";
          } else {
            ctx.fillStyle = "#fff2c9";
          }
          ctx.beginPath();
          ctx.arc(width, width, this.turnplate.outsideRadius, angle, angle + arc, false);    
          ctx.arc(width, width, this.turnplate.insideRadius, angle + arc, angle, true);
          ctx.stroke();  
          ctx.fill();
          //锁画布(为了保存之前的画布状态)
          ctx.save();  
          //奖品默认字体颜色
          // this.ctx.fillStyle = "#fff";
          ctx.fillStyle = "#000";
          let text = this.winnerList[i].it_title;
          ctx.translate(
            width + Math.cos(angle + arc / 2) * (width - 20 ),
            width + Math.sin(angle + arc / 2) * (width - 20)
          );
          ctx.rotate(angle + arc / 2 + Math.PI / 2);
          //将字体绘制在对应坐标
          ctx.font="bold 26px Georgia"
          ctx.shadowColor="#ff7733"
          ctx.shadowOffsetX=0
          ctx.shadowOffsetY=0
          ctx.shadowBlur=1
          ctx.fillStyle="#f66"
          ctx.strokeStyle="#ff7733"
          ctx.lineWidth=2
          if(text.length>=4){//奖品名称长度超过一定范围 
					  text = text.substring(0,4)+"||"+text.substring(4);
					  var texts = text.split("||");
					  for(var j = 0; j<texts.length; j++){
						   ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, 40 * (j + 1));  
						  //  ctx.strokeText(texts[j], -ctx.measureText(texts[j]).width / 2, 40 * (j + 1));  
            }
          }else{
            ctx.fillText(text, -ctx.measureText(text).width / 2, 54);
            // ctx.strokeText(text, -ctx.measureText(text).width / 2, 54);
          }
          
  
          ctx.restore();
          //绘制奖品图片
          // if (this.winnerList[i].it_pic) {
          //   let img = new Image();
          //   img.src = this.winnerList[i].it_pic;
          //   img.onload = () => {
          //     ctx.save();
          //     ctx.translate(
          //       width + Math.cos(angle + arc / 2) * (width - 40),
          //       width + Math.sin(angle + arc / 2) * (width - 40)
          //     );
          //     ctx.rotate(angle + arc / 2);
          //     ctx.drawImage(img, -ctx.measureText(text).width / 2 - 60, -35, 60, 60);
          //     ctx.restore();
          //   };
          // }
        }
      }  
    },
    init() {

    },
    download(){
      handle.goToApp()
    },
    saveWinData(){
      this.$toast('请使用手机截图保存')
      setTimeout(()=>{
        this.saveImg()
      },3000)
      
    },
    shareData(){
      this.overlayShow3=false
      this.shareAddNum()
    },
    shareAddNum(){
      if(!this.isShare){
        this.overlayShow2=false
        setTimeout(()=>{
          this.addUserPrizeNumDeal()
          this.isShare=true
        },3000)
        
      }else{
        this.$toast('分享次数达到上限')
      }
    },
    shareLeave(){
      this.overlayShow2=false
      this.overlayShow3=false
    },
    closeOverlayShow2(){
      this.overlayShow3=true
    },
    startAgain(){
      this.overlayShow2=false
      this.start()
    },
    async showWinData(){
      await this.checkCjUserIsTrue()
      if(JSON.stringify(this.WinInfo)=='{}')return this.$toast('暂无中奖记录哦')
      this.$toast('建议使用手机截图保存')
      this.overlayShow1=true
    },
    winClose(){
      this.overlayShow1=false
      this.WinInfo={}
    },
    saveImg(){//在h5中兼容性不太好,建议直接用户截图
      html2canvas(document.querySelector('#lottery'),{useCORS:true}).then( (canvas)=> {
        //获取年月日作为文件名
        var timers=new Date();
        var fullYear=timers.getFullYear();
        var month=timers.getMonth()+1;
        var date=timers.getDate();
        var randoms=Math.random()+'';
        //年月日加上随机数
        var numberFileName=fullYear+''+month+date+randoms.slice(3,10);
        var imgData=canvas.toDataURL();
        var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
            save_link.href = imgData;
            
        var filename = '中奖'+numberFileName + '.png';
        save_link.download = filename;

        var event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        save_link.dispatchEvent(event);
      })
    },
    showOverlay(){
      this.overlayShow=true
      this.setIntervalTimer= setInterval(()=>{
        this.countTimer--;
        if(this.countTimer<=0){
          clearInterval(this.setIntervalTimer)
          this.goComplete()
        }
      },1000)
    },
    closeOverLay(){
      this.overlayShow=false
      clearInterval(this.setIntervalTimer)
    },
    goComplete(){//跳转的url需要注意一下
      location.href=this.resumeUrl
    },
    
    async start(){//已登录,(绑定手机号) 并且是简历完善的情况下,才能继续
      if(this.numberSum<=0)return this.$toast('抽奖次数不足')
      if(!this.isBindMobile)return this.$toast('请先绑定手机号后,在进行抽奖活动')

      //TODO ,判断好抽奖次数, 对于已中奖的做一次逻辑判断,直接不在中奖,抽一次减一,小于0直接提示无了(对于奖品数没有了,还需做一次逻辑判断)
      await this.checkResumeComplete()//判断简历是否完善(可能会存在异步问题)
      if(!this.iscomplete)return this.$toast('简历未完善');
      
      if(this.turnplate.bRotate)return;
        this.turnplate.bRotate = !this.turnplate.bRotate;
        //获取随机数(奖品个数范围内)
        // 中奖率randomRate TODO,注意好对应字段名
        let randomRate=[]
        for(var i=0;i<this.winnerList.length;i++){
            randomRate.push(Number(this.winnerList[i].it_rate))      
        }
        var item = this.rnd1(randomRate); //拿到抽奖(item, 注: 从1开始)
        console.log('列表',item);
        //TODO对于已中奖的做一次逻辑判断,直接不在中奖,抽一次减一,小于0直接提示无了(对于奖品数没有了,还需做一次逻辑判断)
        /**
         * 做一次篡改,让其不中奖
         * bug(打印undefined???)
         * */ 
        await this.checkCjUserIsTrue()
        if(this.isWin||Number(this.winnerList[item-1].it_total)<=0){
            item=1// 默认为未中奖的这一条
        }
        if(item==1){
          //TODO, 请求未中奖(次数)
          await this.deductUserPrizeNumDeal()
        }else{
          //先请求中奖接口, 在请求减一
          await this.addUserTrueDeal(this.winnerList[item-1].cj_item_id)//注: 抽奖次数与中奖请求接口分开
          await this.deductUserPrizeNumDeal()
        }

        this.rotateFn(item, this.winnerList[item-1]);//进行转动展示
        //TODO, 将结果返回后端,判断中奖状态(isWin的状态值改变),抽奖次数的改变, 对应已中奖数量的改变
        // TODO 需要重新请求数据列表, 判断奖品数
        await this.getLuckdrawPrizeList()
    },
    rnd(rate){//随机从1到100中取值(核心抽奖)
      var random = Math.floor(Math.random() * 100);
      var myRandom = [];
      var randomList = [];
      var randomParent = [];
      for(var i = 0; i < 100; i++){
          myRandom.push(parseInt([i]) + 1);
      }
      for(var i = 0; i < rate.length; i++){
          var temp = [];
          var start = 0;
          var end = 0;
          randomList.push(parseInt(rate[i]));
          for(var j = 0; j < randomList.length; j++){
              start += randomList[j-1] || 0
              end += randomList[j]
          }
          temp = myRandom.slice(start, end);
          randomParent.push(temp)
      }
      console.log(1111,random,randomList);

      for(var i = 0; i < randomParent.length; i++){
          if($.inArray(random, randomParent[i]) > 0){
              return(i+1)
          }
      }
    },
    rnd1(rate){//随机从1到100中取值(核心抽奖)(动态设置)rate从大到小的概率数组
      let sum=rate.reduce((a,b)=>{
        return (a+b)
      })
      var random = Math.random() * sum;
      for (let i=0,sn=0; i<rate.length;i++){
          if((sn+=rate[i])>=random){
            // console.log(sum,sn,random);
            return (i+1)
          }
        }
      },
    rotateFn (item, txt){//提示,以及旋转
      var angles = item * (360 / this.winnerList.length) - (360 / (this.winnerList.length*2));
      if(angles<270){
          angles = 270 - angles; 
      }else{
          angles = 360 - angles + 270;
      }
      $('#wheelCanvas').stopRotate();
      $('#wheelCanvas').rotate({
          angle:0,
          animateTo:angles+1800,
          duration:8000,
          callback: ()=>{
              if(item==1){
                this.overlayShow2=true
                this.shareMsg=this.winnerList[item-1].it_title
              }else{
                this.showWinData()
                // this.overlayShow1=true
                // this.WinInfo=this.winnerList[item-1]
              }
              this.turnplate.bRotate = !this.turnplate.bRotate;
          }
      });
    },

  },
};
</script>



<style scoped>
.show {
  height: 413vw;
  width: 100vw;
  /* background: url('../../../assets/lotteryBg.gif'); */ 
  background-size: 100% 100%;
  background-repeat:no-repeat;
  position: relative;
  overflow: hidden;
}
.yq-lottery {
	height: calc(80vh);
}
.lottery-num {
  position: absolute;
  top: 8%;
  left: 50%;
  transform: translateX(-50%);
  font-size: 18px;
  font-weight: bold;
  color: #1b4e9f;
  text-align: center;
}
.lottery-num p{

}
/* .turnplate {
	margin-top: 100px;
	background: url("../../../assets/turnplate-bg.png");
	background-size: 100% 100%;
} */
/* 大转盘样式 */
.lottery {
	width: 80%;
	margin: auto;
	display: flex;
	justify-content: center;
	align-items: center;
}
.lottery .turnplate {
	display: block;
	width: 100%;
	position: absolute;
  width: 72%;
  top: 20%;
	background-size: 100% 100%;
}
.lottery .turnplate canvas.item {
	width: 100%;
}
.lottery .turnplate img.pointer {
	position: absolute;
  width: 64px;
  top: 38%;
  left: 50%;
  transform: translateX(-50%);
	/* width: 31.5%;
	height: 42.5%;
	left: 34.6%;
	top: 23%; */
}

.start-btn{
  position: absolute;
  top: 618px;
  left: 50%;
  transform: translateX(-50%);
  width: 87%;
  margin: auto;
  height: 80px;
  box-sizing: border-box;
	background-color: #ffe611;
	border-radius: 12px;
	border: solid 3px #1b4e9f;

  display: flex;
  align-items: center;
  justify-content: center;
}
.start-font{
  font-size: 30px;
  font-weight: bold;
  color: #064cc1;
  animation:mymove .5s infinite;
  margin-top: -4px;
}
@keyframes mymove
	{
	from {transform:scale(1);}
	to {transform:scale(1.1);}
}

.record-btn{
  position: absolute;
  top: 707px;
  width: 87%;
  left: 50%;
  transform: translateX(-50%);
	height: 37px;
  box-sizing: border-box;
  border-radius: 7px;
	border: solid 2px #1b4e9f;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}
.record-font{
  font-size: 16px;
	font-weight: bold;
  color: #064cc1;
}

.rule-btn{
  position: absolute;
  top: 753px;
  width: 53.3%;
  left: 23%;
  height: 32px;
	border-radius: 7px;
	border: solid 2px #1b4e9f;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
}
.rule-font{
  font-size: 12px;
	font-weight: bold;
  color: #064cc1;
}
.reward-title{
  text-align: center;
}
.reward-list{
  /* width: 70%;
  height: 300px;
  margin: auto;
  overflow-y: scroll;
  border:1px solid #000; */
  width: 80%;
	height: 406px;
	background-color: #1b4e9f !important;
	border-radius: 11px;
 
  overflow-y: scroll;
  position: absolute;
  top: 1058px;
  left: 10%;
}

::-webkit-scrollbar{
  width: 0;
  height: 0;
}

/* 遮掩层 */
.wrapper {
    /* display: flex;
    align-items: center;
    justify-content: center;
    flex-flow: column;
    height: 100%; */
  }
  .wrapper .wrapper-confirm{
    width: 76%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
  }
  .wrapper .wraper-close{
    width: 18px;
    position: absolute;
    top: 35%;
    right: 17%;
  }
  .wrapper .resume-block{
    position: absolute;
    top: 38%;
    left: 50%;
    transform: translateX(-50%);
    font-size: 14px;
    color: #064cc1;
  }
  .wrapper .resume-btn{
    position: absolute;
    top: 59.5%;
    left: 50%;
    transform: translateX(-50%);
    font-size: 22px;
    font-weight: bold;
    color: #064cc1;
  }

  .block {
    width: 120px;
    height: 120px;
    background-color: #fff;
  }

  .wrapper1{
    width: 100%;
    height: 100%;
    /* background: url('../../../assets/winBg.png'); */
    background-size: 100% 100%;
    background-repeat:no-repeat;
    position: relative;
  }
  .wrapper1 .win-icon{
    position: absolute;
    top: 24%;
    width: 95px;
    left: 50%;
    transform: translateX(-50%);
  }
  .wrapper1 .win-close{
    position: absolute;
    bottom: 10%;
    width: 34px;
    left: 50%;
    transform: translateX(-50%);
  }
  .wrapper1 .win-block{
    position: absolute;
    top: 40%;
    text-align: center;
  }
  .wrapper1 .win-block .win-title{
    font-size: 18px;
    font-weight: bold;
    color: #0f3dbf;
    margin-top: 10px;
    /* margin-bottom: 20px; */
    
  }
  .win-code{
    color: #ed3a71;
  }
  .wrapper1 .win-block .win-tips{
    font-size: 13px;
    color: #1e49c2;
    display: flex;
    justify-content: center;
  }
  .win-block .win-tips div{
    width: 70%;
  }
  .wrapper1 .win-save{
    position: absolute;
    top: 65%;
    left: 50%;
    transform: translateX(-50%);
    font-size: 22px;
    font-weight: bold;
    color: #064cc1;
  }
  .wrapper1 .win-down{
    position: absolute;
    top: 76%;
    left: 50%;
    transform: translateX(-50%);
    font-size: 16px;
    font-weight: bold;
    color: #064cc1;
  }
  .wrapper .share-close{
    position: absolute;
    top: 10%;
    right: 12.05%;
    width: 24px;
  }
  .wrapper .share-point{
    position: absolute;
    top: 2%;
    right: 3%;
    width: 34px;
  }
  .wrapper .share-confirm{
    position: absolute;
    /* top: 50%; */
    top: 184px;
    left: 50%;
    width: 76.4%;
    transform: translateX(-50%);
  }
  .wrapper .tip-title{
    top: 124px;
    width: 250px;
  }
  .wrapper .tip-eye{
    width: 52px;
    top: 190px;
    left: 22%;
    z-index: 1;
  }
  .wrapper .tip-btn{
    top: 468px;
    width: 285.5px;
  }
  .wrapper .share-msg{
    position: absolute;
    top: 80px;
    left: 50%;
    width: 60%;
    transform: translateX(-50%);
    font-size: 14px;
    font-weight: bold;
    color: #fff;
    text-align: center;
  }
  .wrapper .share-tip{
    position: absolute;
    top: 185px;
    left: 50%;
    width: 60%;
    transform: translateX(-50%);
    font-size: 12px;
    font-weight: bold;
    color: #1b4e9f;
    text-align: center;
    width: 285.5px;

    background-color: #ffffff;
    border-radius: 12px;
    border: solid 2.5px #1b4e9f;
    padding: 30px;
    padding-top: 40px;
    box-sizing: border-box;
  }
  .wrapper .share-font{
    position: absolute;
    /* top: 63%; */
    top: 485px;
    left: 50%;
    width: 80%;
    transform: translateX(-50%);
    font-size: 11px;
    font-weight: normal;
    color: #222222;
    text-align: center;
  }
  .share-leave-confirm{
    position: absolute;
    top: 200px;
    left: 50%;
    width: 76.13%;
    transform: translateX(-50%);
  }
  .leave-content{
    position: absolute;
    /* top: 40%; */
    top: 266.8px;
    font-size: 16px;
    font-weight: bold;
    color: #222222;
    text-align: center;
    left: 50%;
    width: 80%;
    transform: translateX(-50%);
  }
  .leave-tip{
    position: absolute;
    /* top: 57.6%; */
    top: 382px;
    left: 50%;
    width: 80%;
    transform: translateX(-50%);
    font-size: 22px;
    font-weight: bold;
    color: #064cc1;
    text-align: center;
  }
  .leave-font{
    position: absolute;
    /* top: 68%; */
    top: 454px;
    left: 50%;
    width: 80%;
    transform: translateX(-50%);
    font-size: 16px;
    font-weight: bold;
    color: #064cc1;
    text-align: center;
  }
  .wrapper .share-again{
    /* top: 63%; */
    top: 485px;
    width: 285.5px;
    height: 50.5px;
    box-sizing: border-box;
    background-color: #ffe611;
    border-radius: 7px;
    border: solid 1.5px #1b4e9f;
    font-size: 16px;
    font-weight: bold;
    color: #064cc1;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .wrapper-rule{
    display: flex;
    flex-flow: column;
    color: #fff;
    padding: 50px 30px;
    font-size: 16px;
  }
  .wrapper-rule p{
    padding: 10px;
  }
  .go-back{
    position: fixed;
    top: 5%;
    right: 0;
    z-index: 1;
    font-size: 16px;
    color: #e13e3e;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 40px;
    background: #fff;
    border-radius: 25px 0 0 25px;
    box-shadow: 0 0 6px #064cc1;
    padding:0 20px;
    padding-right: 10px;
  }
  .wrapper .back-spring{
    position: absolute;
    /* top: 72%; */
    top: 550px;
    width: 285.5px;
    height: 50.5px;
    box-sizing: border-box;
    background-color: #ffe611;
    border-radius: 7px;
    border: solid 1.5px #1b4e9f;
    font-size: 16px;
    font-weight: bold;
    color: #064cc1;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .change-bg{
    background: rgb(0, 0, 0,.8);
  }
</style>